package com.fengqilin.projectlplc;

public class Utils {
    private String appendRCmd(String cmd) {
        StringBuilder sb1 = new StringBuilder();
        StringBuilder sb = new StringBuilder();
        sb.append(cmd.charAt(0));
        sb.append(repeat("0", 6 - cmd.length()));
        sb.append(cmd.substring(1));
        char[] charArray = {'D', 'B', 'F'};
        if (containsChar(charArray, cmd.charAt(0))) {
            sb1.append("01WRD");
            sb1.append(sb);
            if ("D2516".equals(cmd)) {
                sb1.append(",02");
            } else {
                sb1.append(",01");
            }
        } else {
            sb1.append("01BRD");
            sb1.append(sb);
            sb1.append(",001");
        }
        sb1.append("\r\n");
        return sb1.toString();
    }

    public static String appendCmd(String cmd, int value) {
        StringBuilder sb1 = new StringBuilder();
        StringBuilder sb = new StringBuilder();
        sb.append(cmd.charAt(0));
        sb.append(repeat("0", 6 - cmd.length()));
        sb.append(cmd.substring(1));
        char[] charArray = {'D', 'B', 'F'};
        if (containsChar(charArray, cmd.charAt(0))) {
            sb1.append("01WWR");
            sb1.append(sb);
            StringBuilder sb2 = new StringBuilder();
            String varData = Integer.toHexString(value).toUpperCase();
            if ("D2516".equals(cmd)) {
                sb1.append(",02,");
                if (8 - varData.length() > 0) sb2.append(repeat("0", 8 - varData.length()));
                sb2.append(varData);
                sb1.append(sb2.substring(4));
                sb1.append(sb2.substring(0, 4));
            } else {
                sb1.append(",01,");
                if (4 - varData.length() > 0) sb1.append(repeat("0", 4 - varData.length()));
                sb1.append(varData);
            }
        } else {
            sb1.append("01BWR");
            sb1.append(sb);
            sb1.append(",001,");
            sb1.append(value >= 1 ? "1" : "0");
        }
        sb1.append("\r\n");
        return sb1.toString();
    }

    public static boolean containsChar(char[] array, char value) {
        for (char c : array) {
            if (c == value) {
                return true; // 如果找到值，返回true
            }
        }
        return false; // 如果没有找到值，返回false
    }

    public static String repeat(String str, int times) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < times; i++) {
            sb.append(str);
        }
        return sb.toString();
    }

    public static int findIndex(String[] array, String value) {
        for (int i = 0; i < array.length; i++) {
            if (value.equals(array[i])) {
                return i;
            }
        }
        return -1; // 如果没有找到值，返回false
    }
}
